using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace DTOSW.Core.Membership.Functions
{
    public class PasswordEncrypt
    {
  

        
        // byte form of plaintext
        byte[] plainbytes;

        // creating instance of DES class
        SymmetricAlgorithm desObj = DES.Create();

        public string Encrypt(string password)
        {
            byte[] cipherbytes;

            plainbytes = Encoding.ASCII.GetBytes(password);
            // generating symmetric key
            desObj.GenerateKey();
            // generating vector
            desObj.GenerateIV();
            // choose other appropriate modes (CBC, CFB, CTS, ECB, OFB)
            desObj.Mode = CipherMode.CBC;
            // setting the padding mode
            desObj.Padding = PaddingMode.PKCS7;
            // --------------- ECRYPTION ---------------
            // memory stream used as a target to write enrypted data
            MemoryStream ms = new MemoryStream();
            // transforms and encrypts plaintext data to memorystream object
            CryptoStream cs = new CryptoStream(ms,
                desObj.CreateEncryptor(),
                CryptoStreamMode.Write);
            cs.Write(plainbytes, 0, plainbytes.Length);
            cs.Close();
            // getting encrypted data from memorystream to bytes
            cipherbytes = ms.ToArray();
            ms.Close();

            
            return Encoding.ASCII.GetString(cipherbytes);

        }
        public string Decryption(byte[] password)
        {
            MemoryStream ms1 = new MemoryStream(password);
            CryptoStream cs1 = new CryptoStream(ms1, desObj.CreateDecryptor(), CryptoStreamMode.Read);
            // allocate array of bytes equal on lenght with ciphertext array
            plainbytes = new Byte[password.Length];
            // decrypt the ciphertext from previous section
            cs1.Read(plainbytes, 0, password.Length);
            cs1.Close();
            ms1.Close();


            return Encoding.ASCII.GetString(plainbytes);
        }

    }
}